package com.example.stlink.activitys.fragmentChild.activityUserInfo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.stlink.R;
import com.example.stlink.configs.GlideEngine;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.activityUtil.ImgUploadUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class UserInfoDetail extends AppCompatActivity {

    private ConstraintLayout clHeadImg;
    private ConstraintLayout clUserName;
    private ConstraintLayout clSchoolName;
    private ConstraintLayout clRealName;
    private ConstraintLayout clIdNumber;
    private ConstraintLayout clSex;
    private ConstraintLayout clCreateTime;
    private ConstraintLayout clEmail;
    private ConstraintLayout clPhone;

    private ImageView ivHeadImg;
    private TextView tvUserNameMsg;
    private TextView tvSchoolMsg;
    private TextView tvRealNameMsg;
    private TextView tvIdNumberMsg;
    private TextView tvSexMsg;
    private TextView tvCreateTimeMsg;
    private TextView tvEmailMsg;
    private TextView tvPhoneMsg;
    private TextView tvIdNumber;
    private ImageView abIvTitle;

    private Bundle bundle;

    private Handler imgUploadHandler;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

//    private ArrayList<String> arrayList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail_my_info);
        CommonUtils.changeStatusBar(this);

        initView();
    }


    /**
     * 初始化页面
     */
    public void initView(){
        clHeadImg = findViewById(R.id.cl_head_img);
        clUserName = findViewById(R.id.cl_user_name);
        clSchoolName = findViewById(R.id.cl_school_name);
        clRealName = findViewById(R.id.cl_real_name);
        clIdNumber = findViewById(R.id.cl_id_number);
        clSex = findViewById(R.id.cl_sex);
        clCreateTime = findViewById(R.id.cl_create_time);
        clEmail = findViewById(R.id.cl_email);
        clPhone = findViewById(R.id.cl_phone);

        ivHeadImg = findViewById(R.id.iv_head_img);
        tvUserNameMsg = findViewById(R.id.tv_user_name_msg);
        tvSchoolMsg = findViewById(R.id.tv_school_msg);
        tvRealNameMsg = findViewById(R.id.tv_real_name_msg);
        tvIdNumberMsg = findViewById(R.id.tv_id_number_msg);
        tvSexMsg = findViewById(R.id.tv_sex_msg);
        tvCreateTimeMsg = findViewById(R.id.tv_create_time_msg);
        tvEmailMsg = findViewById(R.id.tv_email_msg);
        tvPhoneMsg = findViewById(R.id.tv_phone_msg);
        tvIdNumber = findViewById(R.id.tv_id_number);
        abIvTitle = findViewById(R.id.ab_iv_title);

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            System.out.println("registerForActivityResult...........................");
            if (resultCode == RESULT_OK) {
                assert data != null;
                getIntent().putExtras(data.getExtras());
                refreshData();
            }
        });

        refreshData();

        imgUploadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                bundle = (Bundle) msg.obj;
                if(bundle.getBoolean(UrlConstants.IS_IMG_UPLOAD_SUCCESS)){
                    System.out.println("refreshData..................");
                    getIntent().putExtras(bundle);
                    refreshData();
                }else{
                    Toast.makeText(UserInfoDetail.this, "修改失败", Toast.LENGTH_SHORT).show();
                }
            }
        };

        initOnClickListener();
    }

    private void refreshData(){
        bundle = getIntent().getExtras();
        int roleId = bundle.getInt(ModelFieldConstants.ROLE_ID);
        String avatar = (String) bundle.get(ModelFieldConstants.AVATAR);
        String schoolName = (String) bundle.get(ModelFieldConstants.COLLEGE_NAME);
        String userNameMsg = (String) bundle.get(ModelFieldConstants.USER_NAME);
        String realNameMsg = (String) bundle.get(ModelFieldConstants.REAL_NAME);
        Long idNumberMsg = (Long) bundle.get(ModelFieldConstants.ID_NUMBER);
        boolean sexMsg = bundle.getBoolean(ModelFieldConstants.GENDER);
        Long createTimeMsg = (Long) bundle.get(ModelFieldConstants.CREATE_TIME);
        String emailMsg = (String) bundle.get(ModelFieldConstants.EMAIL);
        String phoneMsg = (String) bundle.get(ModelFieldConstants.PHONE);

        if(roleId == 0){
            ivHeadImg.setImageResource(R.mipmap.student);
            tvIdNumber.setText("学号");
        }
        if(avatar != null){
            Glide.with(getApplicationContext())
                    .load(avatar)
                    //添加圆角
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                    .into(ivHeadImg);
        }
        if(schoolName != null){
            tvSchoolMsg.setText(schoolName);
        }
        if(userNameMsg != null){
            tvUserNameMsg.setText(userNameMsg);
        }
        if(realNameMsg != null){
            tvRealNameMsg.setText(realNameMsg);
        }
        if(idNumberMsg != null){
            tvIdNumberMsg.setText(String.valueOf(idNumberMsg));
        }
        if(sexMsg){
            tvSexMsg.setText("男");
        }else{
            tvSexMsg.setText("女");
        }
        if(createTimeMsg != null){
            Date date = new Date(createTimeMsg);
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            tvCreateTimeMsg.setText(sd.format(date));
        }
        if(emailMsg != null){
            tvEmailMsg.setText(emailMsg);
        }
        if(phoneMsg != null){
            tvPhoneMsg.setText(phoneMsg);
        }

    }

    /**
     * 初始化按钮事件
     */
    public void initOnClickListener(){
        //头像
        clHeadImg.setOnClickListener(v -> {
            // 调用第三方开源图片库
            PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())    // 图片加载引擎
                .setMaxSelectNum(1)// 最大图片选择数量 int
                .setImageSpanCount(4)// 每行显示个数 int
                .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选
                .isPreviewImage(true)// 是否可预览图片 true or false
                .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isGif(false) //是否显示gif文件
                .isWebp(false) //是否显示webp文件
                .isBmp(false) //是否显示bmp文件
                .isMaxSelectEnabledMask(true) //达到最大选择数是否开启禁选蒙层
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        LocalMedia localMedia = result.get(0);
                        String path = localMedia.getRealPath();
                        ImgUploadUtil.userImgUpload(bundle, imgUploadHandler, path, ModelFieldConstants.AVATAR);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
        });
        clUserName.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.USER_NAME);
            intent.putExtras(bundle);

            intentActivityResultLauncher.launch(intent);
        });
        clSchoolName.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.COLLEGE_NAME);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        clRealName.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.REAL_NAME);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        clIdNumber.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.ID_NUMBER);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        clSex.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.GENDER);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        clCreateTime.setOnClickListener(v -> {
        });
        clEmail.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.EMAIL);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        clPhone.setOnClickListener(v -> {
            Intent intent = new Intent(UserInfoDetail.this, ModifyUserInfo.class);
            Bundle bundle = getIntent().getExtras();
            bundle.putString(ModelFieldConstants.TO_BE_MODIFY, ModelFieldConstants.PHONE);
            intent.putExtras(bundle);
            intentActivityResultLauncher.launch(intent);
        });
        //返回上一个活动，也就是个人信息部分
        abIvTitle.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtras(bundle);
            setResult(RESULT_OK,intent);
            finish();
        });

    }
}
